<?php

namespace App\Http\Controllers;

use App\Handlers\ImageUploadHandler;
use App\Models\Category;
use App\Models\Link;
use App\Models\Topic;
use App\Http\Requests\StoreTopicRequest;
use App\Http\Requests\UpdateTopicRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;


class TopicController extends Controller {
    public function __construct() {
        $this->middleware('auth')->except(['index','show']);
    }

    public function index(Request $request, Topic $topic,User $user,Link $link) {
        $topics = $topic->withOrder($request->order)->with('user', 'category')->paginate(10);
        $active_users = $user->getActiveUsers();
        $links = $link->getAllCache();
        return view('topics.index', compact('topics','active_users','links'));
    }


    public function create() {
        $categories = Category::all();
        return view('topics.create', compact('categories'));
    }

    public function store(StoreTopicRequest $request, Topic $topic) {
        $topic->fill($request->all());
        $topic->user_id = Auth::id();
        $topic->save();
        return redirect()->to($topic->link())->with('success', '帖子新建成功');
    }


    public function show(Request $request,Topic $topic) {
        if(!empty($topic->slug) && $topic->slug != $request->slug){
            return redirect($topic->link(),301);
        }
        $replies = $topic->replies()->with('user')->get();
        return view('topics.show', compact('topic','replies'));
    }


    public function edit(Topic $topic) {
        $this->authorize('update',$topic);
        $categories = Category::all();
        return view('topics.edit',compact('topic','categories'));
    }

    public function update(UpdateTopicRequest $request, Topic $topic) {
        $this->authorize('update',$topic);
        $topic->update($request->all());
        return redirect()->to($topic->link())->with('success', '更新成功');
    }


    public function destroy(Topic $topic) {
        $this->authorize('delete',$topic);
        $topic->delete();
        return redirect()->route('topic.index')->with('success','删除成功');
    }

    //富文本编辑器上传图片
    public function uploadImage(Request $request, ImageUploadHandler $uploader) {
        $data = [
            'success' => false,
            'msg' => '上传失败!',
            'file_path' => ''
        ];
        if($file = $request->upload_file){
            $result = $uploader->save($file,'topics',Auth::id(),1024);
            if($result){
                $data['file_path'] = $result['path'];
                $data['msg']='上传成功!';
                $data['success'] = true;
            }
        }
        return $data;
    }
}
